<template>
  <AdminLayout title="仪表板概览" subtitle="查看您的业务数据和关键指标">

    <!-- 第一行：核心统计卡片 -->
    <div class="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4 mb-8">
      <!-- 总销售额 -->
      <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200 hover:shadow-md transition-shadow">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">总销售额</p>
            <p class="text-2xl font-light text-gray-900 mt-2">¥{{ formatNumber(stats.totalSales) }}</p>
            <p class="text-xs text-gray-500 mt-1">今日：¥{{ formatNumber(stats.todaySales) }}</p>
          </div>
          <div class="w-12 h-12 bg-green-50 rounded-lg flex items-center justify-center">
            <svg class="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 10v1m-4-8H4m12 0h4m-2-4h2m-2 8h2M6 12H4m12 0h4m-2-4h2m-2 8h2"></path>
            </svg>
          </div>
        </div>
      </div>

      <!-- 总订单数 -->
      <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200 hover:shadow-md transition-shadow">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">总订单数</p>
            <p class="text-2xl font-light text-gray-900 mt-2">{{ formatNumber(stats.totalOrders) }}</p>
            <p class="text-xs text-gray-500 mt-1">今日：{{ stats.todayOrders }}</p>
          </div>
          <div class="w-12 h-12 bg-blue-50 rounded-lg flex items-center justify-center">
            <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"></path>
            </svg>
          </div>
        </div>
      </div>

      <!-- 待处理订单 -->
      <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200 hover:shadow-md transition-shadow">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">待处理订单</p>
            <p class="text-2xl font-light text-gray-900 mt-2">{{ stats.pendingOrders }}</p>
            <Link :href="route('admin.orders.index')" class="text-xs text-blue-600 hover:text-blue-800 mt-1 inline-block">
              立即处理 →
            </Link>
          </div>
          <div class="w-12 h-12 bg-orange-50 rounded-lg flex items-center justify-center">
            <svg class="w-6 h-6 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
          </div>
        </div>
      </div>

      <!-- 库存警告 -->
      <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200 hover:shadow-md transition-shadow">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">库存警告</p>
            <p class="text-2xl font-light text-gray-900 mt-2">{{ stats.lowStockProducts }}</p>
            <p class="text-xs text-gray-500 mt-1">需要补货的产品</p>
          </div>
          <div class="w-12 h-12 bg-red-50 rounded-lg flex items-center justify-center">
            <svg class="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
            </svg>
          </div>
        </div>
      </div>
    </div>

    <!-- 第二行：销售趋势和订单状态 -->
    <div class="grid grid-cols-1 gap-6 lg:grid-cols-3 mb-8">
      <!-- 销售趋势图 -->
      <div class="lg:col-span-2 bg-white p-6 rounded-lg shadow-sm border border-gray-200">
        <h3 class="text-lg font-medium text-gray-900 mb-4">销售趋势（最近7天）</h3>
        <div class="h-64">
          <canvas ref="salesChart"></canvas>
        </div>
      </div>

      <!-- 订单状态分布 -->
      <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
        <h3 class="text-lg font-medium text-gray-900 mb-4">订单状态分布</h3>
        <div class="space-y-4">
          <div v-for="(count, status) in orderStatusDistribution" :key="status" class="flex items-center justify-between">
            <div class="flex items-center">
              <div :class="getStatusColor(status)" class="w-3 h-3 rounded-full mr-3"></div>
              <span class="text-sm text-gray-700">{{ getStatusText(status) }}</span>
            </div>
            <span class="text-sm font-medium text-gray-900">{{ count }}</span>
          </div>
        </div>
        <div class="mt-6 pt-6 border-t border-gray-200">
          <canvas ref="statusChart"></canvas>
        </div>
      </div>
    </div>

    <!-- 第三行：分类销售和低库存产品 -->
    <div class="grid grid-cols-1 gap-6 lg:grid-cols-2 mb-8">
      <!-- 分类销售统计 -->
      <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-medium text-gray-900">分类销售排行</h3>
          <Link :href="route('admin.categories.index')" 
                class="text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors duration-200">
            查看全部
          </Link>
        </div>
        <div class="space-y-4">
          <div v-for="(category, index) in categorySales" :key="index" class="flex items-center">
            <div class="flex-shrink-0 w-8 h-8 bg-gray-100 rounded-lg flex items-center justify-center">
              <span class="text-xs font-medium text-gray-700">#{{ index + 1 }}</span>
            </div>
            <div class="ml-4 flex-1">
              <p class="text-sm font-medium text-gray-900">{{ category.name }}</p>
              <div class="mt-1 flex items-center">
                <div class="flex-1 bg-gray-200 rounded-full h-2">
                  <div 
                    class="bg-blue-600 h-2 rounded-full" 
                    :style="{ width: getCategoryPercentage(category.total_sales) + '%' }"
                  ></div>
                </div>
                <span class="ml-3 text-xs text-gray-600">¥{{ formatNumber(category.total_sales) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 低库存产品 -->
      <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-medium text-gray-900">库存警告</h3>
          <Link :href="route('admin.products.index')" 
                class="text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors duration-200">
            查看全部
          </Link>
        </div>
        <div class="space-y-3">
          <div v-if="lowStockProducts.length === 0" class="text-center py-8">
            <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
            <p class="mt-2 text-sm text-gray-500">所有产品库存充足</p>
          </div>
          <div v-else v-for="product in lowStockProducts" :key="product.id" class="flex items-center justify-between p-3 bg-red-50 rounded-lg">
            <div class="flex-1 min-w-0">
              <p class="text-sm font-medium text-gray-900 truncate">{{ product.name }}</p>
              <p class="text-xs text-gray-600">SKU: {{ product.sku }}</p>
            </div>
            <div class="ml-4 text-right">
              <p class="text-sm font-bold text-red-600">{{ product.stock_quantity }}</p>
              <p class="text-xs text-gray-500">阈值: {{ product.low_stock_threshold }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 第四行：热门产品和最近订单 -->
    <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
      <!-- 热门产品 -->
      <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-medium text-gray-900">热门产品</h3>
          <Link :href="route('admin.products.index')" 
                class="text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors duration-200">
            查看全部
          </Link>
        </div>
        <div class="space-y-4">
          <div v-for="(product, index) in topProducts" :key="product.id" class="flex items-center space-x-4">
            <div class="flex-shrink-0">
              <div class="h-10 w-10 rounded-lg bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
                <span class="text-sm font-bold text-white">#{{ index + 1 }}</span>
              </div>
            </div>
            <div class="min-w-0 flex-1">
              <p class="text-sm font-medium text-gray-900 truncate">{{ product.name }}</p>
              <p class="text-sm text-gray-600">¥{{ formatNumber(product.price) }}</p>
            </div>
            <div class="flex-shrink-0 text-right">
              <p class="text-sm font-medium text-gray-900">{{ product.sales_count }}</p>
              <p class="text-xs text-gray-500">销量</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 最近订单 -->
      <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-medium text-gray-900">最近订单</h3>
          <Link :href="route('admin.orders.index')" 
                class="text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors duration-200">
            查看全部
          </Link>
        </div>
        <div class="space-y-4">
          <div v-for="order in recentOrders.slice(0, 5)" :key="order.id" class="flex items-center space-x-4">
            <div class="flex-shrink-0">
              <div class="h-8 w-8 rounded-full bg-gray-100 flex items-center justify-center">
                <svg class="h-5 w-5 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
                </svg>
              </div>
            </div>
            <div class="min-w-0 flex-1">
              <p class="text-sm font-medium text-gray-900 truncate">
                #{{ order.order_number }}
              </p>
              <p class="text-sm text-gray-600 truncate">
                {{ order.user ? order.user.name : 'N/A' }} - ¥{{ formatNumber(order.total_amount) }}
              </p>
            </div>
            <div class="flex-shrink-0">
              <span :class="getStatusBadgeClass(order.status)" class="inline-flex items-center rounded-full px-2 py-1 text-xs font-medium ring-1 ring-inset">
                {{ getStatusText(order.status) }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

  </AdminLayout>
</template>

<script setup>
import { Link } from '@inertiajs/vue3'
import { ref, onMounted, computed } from 'vue'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import Chart from 'chart.js/auto'

// 定义 props
const props = defineProps({
  stats: {
    type: Object,
    required: true
  },
  topProducts: {
    type: Array,
    default: () => []
  },
  recentOrders: {
    type: Array,
    default: () => []
  },
  salesTrend: {
    type: Array,
    default: () => []
  },
  orderStatusDistribution: {
    type: Object,
    default: () => ({})
  },
  categorySales: {
    type: Array,
    default: () => []
  },
  lowStockProducts: {
    type: Array,
    default: () => []
  }
})

// 图表引用
const salesChart = ref(null)
const statusChart = ref(null)

// 格式化数字
const formatNumber = (num) => {
  return new Intl.NumberFormat('zh-CN').format(num)
}

// 获取状态文本
const getStatusText = (status) => {
  const statusTexts = {
    'pending': '待处理',
    'processing': '处理中',
    'shipped': '已发货',
    'delivered': '已送达',
    'cancelled': '已取消'
  }
  return statusTexts[status] || status
}

// 获取状态颜色
const getStatusColor = (status) => {
  const colors = {
    'pending': 'bg-orange-500',
    'processing': 'bg-blue-500',
    'shipped': 'bg-purple-500',
    'delivered': 'bg-green-500',
    'cancelled': 'bg-red-500'
  }
  return colors[status] || 'bg-gray-500'
}

// 获取状态徽章样式
const getStatusBadgeClass = (status) => {
  const classes = {
    'pending': 'bg-orange-50 text-orange-700 ring-orange-600/20',
    'processing': 'bg-blue-50 text-blue-700 ring-blue-600/20',
    'shipped': 'bg-purple-50 text-purple-700 ring-purple-600/20',
    'delivered': 'bg-green-50 text-green-700 ring-green-600/20',
    'cancelled': 'bg-red-50 text-red-700 ring-red-600/20'
  }
  return classes[status] || 'bg-gray-50 text-gray-700 ring-gray-600/20'
}

// 计算分类销售百分比
const maxCategorySales = computed(() => {
  if (props.categorySales.length === 0) return 0
  return Math.max(...props.categorySales.map(c => c.total_sales))
})

const getCategoryPercentage = (sales) => {
  if (maxCategorySales.value === 0) return 0
  return (sales / maxCategorySales.value) * 100
}

// 初始化图表
onMounted(() => {
  // 销售趋势图
  if (salesChart.value && props.salesTrend.length > 0) {
    new Chart(salesChart.value, {
      type: 'line',
      data: {
        labels: props.salesTrend.map(item => item.date),
        datasets: [
          {
            label: '销售额',
            data: props.salesTrend.map(item => item.sales),
            borderColor: 'rgb(59, 130, 246)',
            backgroundColor: 'rgba(59, 130, 246, 0.1)',
            tension: 0.4,
            fill: true
          },
          {
            label: '订单数',
            data: props.salesTrend.map(item => item.orders),
            borderColor: 'rgb(168, 85, 247)',
            backgroundColor: 'rgba(168, 85, 247, 0.1)',
            tension: 0.4,
            fill: true,
            yAxisID: 'y1'
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        interaction: {
          mode: 'index',
          intersect: false,
        },
        plugins: {
          legend: {
            display: true,
            position: 'top'
          }
        },
        scales: {
          y: {
            type: 'linear',
            display: true,
            position: 'left',
            title: {
              display: true,
              text: '销售额（¥）'
            }
          },
          y1: {
            type: 'linear',
            display: true,
            position: 'right',
            title: {
              display: true,
              text: '订单数'
            },
            grid: {
              drawOnChartArea: false,
            }
          }
        }
      }
    })
  }

  // 订单状态分布饼图
  if (statusChart.value && props.orderStatusDistribution) {
    const statusData = Object.entries(props.orderStatusDistribution).map(([status, count]) => ({
      status,
      count
    }))

    new Chart(statusChart.value, {
      type: 'doughnut',
      data: {
        labels: statusData.map(item => getStatusText(item.status)),
        datasets: [{
          data: statusData.map(item => item.count),
          backgroundColor: [
            'rgb(249, 115, 22)',  // pending - orange
            'rgb(59, 130, 246)',  // processing - blue
            'rgb(168, 85, 247)',  // shipped - purple
            'rgb(34, 197, 94)',   // delivered - green
            'rgb(239, 68, 68)'    // cancelled - red
          ],
          borderWidth: 2,
          borderColor: '#fff'
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false
          }
        }
      }
    })
  }
})
</script>
